<?php
namespace app\admin\controller;
use app\BaseController;
use think\facade\View;
use app\common\model\mysql\AdminUser;
class Login extends BaseController
{
    public function index(){
        return View::fetch();
    }
    public function check(){
        if(!$this->request->isPost()){
            return show(config('status.error'),'请求参数错误');
        }
        //参数校验
        // 获取到参数
        $username = $this->request->param('username','','trim');
        $password = $this->request->param('password','','trim');
        $captcha = $this->request->param('captcha','','trim');
        if(empty($username) || empty($password) || empty($captcha)){
            return show(config('status.error'),'参数不能为空');
        }
        if(!captcha_check($captcha)){
            return show(config('status.error'),'验证码不正确');
        }
        try {
            $adminUserObj = new AdminUser();
            $adminUser    = $adminUserObj->getAdminUserByUsername($username);
            if (empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')) {
                return show(config('status.error'), "不存在该用户");
            }
            $adminUser->toArray();
            if ($adminUser['password'] != md5($password . "_xiaxiang_abc")) {
                return show(config('status.error'), "密码错误");
            }
            // 记录session
            $res = $adminUserObj->updateById($adminUser['id'], [
                'last_login_time' => time(),
                'last_login_ip'   => $this->request->ip(),
            ]);
            if (!$res) {
                return show(config('status.error'), "记录失败。登录失败");
            }
        }catch (\Exception $e){
            //todo 记录日志 $e
            return show(config('status.error'), "内部异常,登录失败");
        }
        session(config('admin.session_admin'),$adminUser);
        return show(config('status.success'),"登录成功");
    }
}